package com.jucai.pppeiyouclient.view.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.adapter.BadgeTabAdapter;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.base.BaseApplication;
import com.jucai.pppeiyouclient.bean.IMUserBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.ScreenUtil;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.StringUtil;
import com.jucai.pppeiyouclient.view.fragment.SystemNewsFragment;
import com.jucai.pppeiyouclient.weidget.BadgeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.model.UIConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * Created by UPC on 2017/4/7.
 */

public class MessageActivity extends BaseActivity {
    private CircleImageView centerImg;
    private TextView centerNick;
    private TabLayout centerTab;
    private ViewPager centerVp;
    private BadgeTabAdapter tabAdapter;
    private String[] titles = new String[]{"用户信息", "系统消息"};
    private List<Fragment> fragments = new ArrayList<>();
    private List<Integer> badgeCountList = new ArrayList<>();
    private List<BadgeView> badgeViews;
    private int position;
    private LinearLayout linearLayout;

    CustomConversationListFragment conversationListFragment;


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_news_center);
        fragments.add(enterFragment());
        fragments.add(new SystemNewsFragment());

        ((TextView) findViewById(R.id.common_title_text)).setText("消息");
        centerImg = (CircleImageView) findViewById(R.id.center_img);
        centerNick = (TextView) findViewById(R.id.center_nick);
        centerTab = (TabLayout) findViewById(R.id.center_tab);
        centerVp = (ViewPager) findViewById(R.id.center_vp);
        tabAdapter = new BadgeTabAdapter(MessageActivity.this,
                getSupportFragmentManager(), fragments, titles, badgeCountList);
        centerTab.setupWithViewPager(centerVp);
        centerVp.setAdapter(tabAdapter);

        linearLayout = (LinearLayout) centerTab.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.shape_vertical_divider_gray));
        linearLayout.setDividerPadding(ScreenUtil.dip2px(this, 15));
    }


    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        Glide.with(this)
                .load(SharedPreferencesUtil.getStringPreference(this, "PREFERENCE", "avatar", ""))
                .centerCrop()
                .override(80, 80)
                .into(centerImg);

        centerNick.setText(SharedPreferencesUtil.getStringPreference(this, "PREFERENCE", "name", ""));

//        badgeCountList.add(89);
//        badgeCountList.add(100);
//        tabAdapter.setBadgeCounts(badgeCountList);

//        initBadgeViews();
//        setUpTabBadge();

        position = getIntent().getIntExtra("position", 0);
        switch (position) {
            case 0:
                centerVp.setCurrentItem(0);
                break;

            case 1:
                centerVp.setCurrentItem(1);
                break;

            default:
                break;
        }
        initRongIm();
        isReconnect();

        Intent i = getIntent();
        if(i != null){
           int screenId = i.getIntExtra("jpush_system_msg",-1);
            if(screenId == 2){
                centerVp.setCurrentItem(2);
            }
        }
    }

    @Override
    protected void loadNetData() {

    }

    private void initRongIm() {
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            @Override
            public UserInfo getUserInfo(String userId) {
                if (!StringUtil.isChinese(userId))
                    getFriendUserInfo(userId);
                return null;//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
            }

        }, true);


        /**
         * 设置会话列表界面操作的监听器。
         */
        RongIM.setConversationListBehaviorListener(new MyConversationListBehaviorListener());
    }

    /**
     * 加载 会话列表 ConversationListFragment
     */
    private ConversationListFragment enterFragment() {
        if (conversationListFragment == null) {
            conversationListFragment = new CustomConversationListFragment();

            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationlist")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话非聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "true")//设置群组会话聚合显示
                    .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//设置讨论组会话非聚合显示
                    .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true")//设置系统会话非聚合显示
                    .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "true")

                    .build();

            conversationListFragment.setUri(uri);
        }
        return conversationListFragment;
    }

    private void initRongIM(){
        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            @Override
            public UserInfo getUserInfo(String userId) {
                if (!StringUtil.isChinese(userId))
                    getFriendUserInfo(userId);
                return null;//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
            }

        }, true);

    }

    private void getFriendUserInfo(String userId) {
        Map<String, String> mapWallet = new HashMap<>();
        mapWallet.put("service", "Public_Chat.getMemberChatData");
        mapWallet.put("target_member_id", userId);

        CommonRequestNetData.getJsonStringDataByEncrpt(MessageActivity.this, mapWallet, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) {
                try {

                    IMUserBean dataBean = new Gson().fromJson(str, IMUserBean.class);
                    RongIM.getInstance().refreshUserInfoCache(new UserInfo(dataBean.rongyun_id, dataBean.rongyun_nickname, Uri.parse(dataBean.rongyun_avatar)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String str) {
                LogUtils.e("jsonObject：" + str);
            }


        });
    }


    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect() {

        Intent intent = getIntent();

        String token = LoginUtils.getRongyun_token(this);


        //push，通知或新消息过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {

            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {

                    reconnect(token);
                } else {
                    enterFragment();
                }
            }
        }
    }

    /**
     * 重连
     *
     * @param token
     */
    private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(BaseApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {
                    RongIM.getInstance().setCurrentUserInfo(new UserInfo(LoginUtils.getRongyun_id(MessageActivity.this),
                            LoginUtils.getMember_nickname(MessageActivity.this), Uri.parse(LoginUtils.getMember_avatar(MessageActivity.this))));

                    tabAdapter.notifyDataSetChanged();
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(MessageActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;
        }
    }

    public static class CustomConversationListFragment extends ConversationListFragment{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            super.onItemClick(parent, view, position, id);
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            return super.onItemLongClick(parent, view, position, id);
        }
    }

    private class MyConversationListBehaviorListener implements RongIM.ConversationListBehaviorListener{

        @Override
        public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {
            return false;
        }

        @Override
        public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
            return false;
        }

        @Override
        public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
            return false;
        }

        @Override
        public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
            if (RongIM.getInstance() != null) {
                RongIM.getInstance().startPrivateChat(MessageActivity.this, uiConversation.getConversationTargetId(), uiConversation.getUIConversationTitle());
                return true;
            }
            return false;
        }
    }

}
